package com.zc.hadoop.mapreduce4;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.WritableComparable;

public class SortCountWritable implements WritableComparable<SortCountWritable> {

	// 要统计数量的key
	private String countKey;
	// 数量
	private int count;

	// 只要数据在网络中传输，就要用到序列化和反序列化

	// 先数据序列化，把对象（字段）写到字节输出流中
	@Override
	public void write(DataOutput out) throws IOException {
		out.writeUTF(countKey);
		out.writeInt(count);
	}

	// 数据反序列话,把对象从字节输出流中读取出来，并且序列化和反序列化的字段顺序要相同
	@Override
	public void readFields(DataInput in) throws IOException {
		this.countKey = in.readUTF();
		this.count = in.readInt();

	}

	/**
	 * 
	 */
	@Override
	public int compareTo(SortCountWritable myWritable) {
		Integer currCount = Integer.valueOf(this.getCount());
		Integer getCount = Integer.valueOf(myWritable.getCount());
		
		// 获取到的对象的count值 > 当前对象的count的值
		int diff = getCount - currCount;
		if (diff > 0) {
			return diff;
		}
		//否者就把 比较两个的key大小的值 输出（compareto方法，返回参与比较的前后两个字符串的asc码的差值）
		return String.valueOf(myWritable.getCountKey()).compareTo(String.valueOf(this.getCountKey()));
	}

	/**
	 * 重写toString ，作为输出
	 */
	@Override
	public String toString() {
		return countKey + "\t" + count;
	}

	// 构造函数（空参）
	public SortCountWritable() {
		super();
	}

	// 构造函数
	public SortCountWritable(String countKey, int count) {
		super();
		this.countKey = countKey;
		this.count = count;
	}

	// get,set

	public String getCountKey() {
		return countKey;
	}

	public void setCountKey(String countKey) {
		this.countKey = countKey;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

}
